/**
 * @description:用户登录注册退出状态管理数据
 * @author:zhangmanyi
 */
import { login, logout, queryUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo:{}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO:(state, userInfo)=>{
    state.userInfo = userInfo
  }
}

const actions = {
  // 用户登录
  login({ dispatch,commit }, userInfo) {
    const { commonKey, authKey } = userInfo

    return new Promise((resolve, reject) => {
      const  params = { commonKey: commonKey.trim(), authKey: authKey }
      login(params).then(res => {
        
        const { data } = res
        const token = 'Bearer' + ' ' + data.access_token  //配合后端token需要拼接
        commit('SET_TOKEN', token)
        setToken(token)

        dispatch('getInfo',commonKey)  // 根据表统一认证号查询用户信息

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 根据表统一认证号查询用户信息
  getInfo({ commit }, commonKey ) {
    queryUserInfo({commonKey}).then(res => {
      commit('SET_USERINFO', res.data)
    }).catch(error => {
      console.log(error)
    })
  
  },
  // 用户退出
  logout({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // 删除 token  用于request.js处理token过期
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
